package com.springboot.exp.exp_3.controllers;

import com.springboot.exp.exp_3.models.RegionStats;
import com.springboot.exp.exp_3.services.CoronaVirusDataService;
import com.sun.javafx.collections.UnmodifiableListSet;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;



@Controller
@RequiredArgsConstructor
public class HomeController {
    //使用构造器注入CoronaVirusDataService
    private final CoronaVirusDataService coronaVirusDataService;

    @GetMapping("/")
    public String home(Model model, String country){
        List<RegionStats> allStats;
        if(country == null)
            allStats = coronaVirusDataService.getAllRegionStats();
        else
            allStats = Collections.unmodifiableList(coronaVirusDataService.getAllRegionStats()
                    .parallelStream()
                    .filter(locationStats -> locationStats.getCountry().equals(country))
                    .collect(Collectors.toList()));

        //设置查询条件
        model.addAttribute("country",country);

        //使用parallelStream统计数据
        int totalReportedCases=allStats.parallelStream().mapToInt(RegionStats::getLatestTotalCases).sum();
        int totalNewCases=allStats.parallelStream().mapToInt(RegionStats::getDiffFromPrevDay).sum();

        model.addAttribute("regionStats",allStats);
        model.addAttribute("totalReportedCases",totalReportedCases);
        model.addAttribute("totalNewCases",totalNewCases);

        //获取当前日期
        model.addAttribute("localDate", LocalDate.now());
        return "index";
    }
}
